from typing import List


class Solution:
    def findMinMoves(self, machines: List[int]) -> int:
        clothes = sum(machines)

        if clothes % len(machines) != 0:
            return -1

        if len(machines) == 1:
            return 0

        avg = clothes // len(machines)

        # ---------- 计算每一个位置的传递情况 ----------
        lst = []
        before = 0
        need = 0
        for i in range(len(machines) - 1):
            before += machines[i]
            need += avg
            lst.append(before - need)

        # ---------- 计算传递的最大值 ----------
        if len(lst) == 1:
            return abs(lst[0])

        # print(lst)

        ans = max(abs(num) for num in lst)
        for i in range(len(lst) - 1):
            if lst[i + 1] > 0 and lst[i] < 0:  # 左右都是出
                ans = max(ans, lst[i + 1] - lst[i])
        return ans


if __name__ == "__main__":
    print(Solution().findMinMoves([1, 0, 5]))  # 3
    print(Solution().findMinMoves([0, 3, 0]))  # 2
    print(Solution().findMinMoves([0, 2, 0]))  # -1

    # 测试用例50
    print(Solution().findMinMoves([1, 3]))  # 1

    # 测试用例51
    print(Solution().findMinMoves([0, 0, 11, 5]))  # 8

    # 测试用例116
    print(Solution().findMinMoves([9, 1, 8, 8, 9]))  # 4
